<template>
  <div ref="ring" class="comp"></div>
</template>

<script setup>
import {
  ref,
  reactive,
  toRefs,
  inject,
  onMounted,
  onBeforeUnmount,
  watch,
} from "vue";
import { useStore } from "vuex";
let store = useStore();
const echarts = inject("echarts");
const api = inject("api");
let ring = ref(null);
let echartsInstance = null;
let alldata = [];

watch(
  () => store.state.themeName,
  () => {
    echartsInstance.dispose();
    initEcharts();
    enitEcharts();
    asisEcharts();
  }
);

function initEcharts() {
  echartsInstance = echarts.init(ring.value, store.state.themeName);
  let initOptions = {
    title: {
      text: "主要地区农作物种植占比",
      top: "3%",
      left: "3%",
    },
  };
  echartsInstance.setOption(initOptions);
}
async function getData() {
  let { data } = await api("cropAreasProportion");
  //   console.log(data);
  alldata = data;
  enitEcharts();
}

function enitEcharts() {
  let count = alldata.length;
  //   console.log(count);
  let setateData = alldata.map((item, index) => {
    console.log(item, index);
    return {
      type: "pie",
      data: [
        { name: item.areas + "\n" + item.zb + "%", value: item.zb },
        { value: item.other },
      ],
      center: [(100 / (count + 1)) * (index + 1) + "%", "50%"],
      label: {
        position: "center",
      },
    };
  });

  let enitOptions = {
    series: setateData,
  };
  echartsInstance.setOption(enitOptions);
  asisEcharts();
}
function asisEcharts() {
  let width = ring.value.offsetWidth;
  let scale = (width / 100) * 3.6;
  let setateData = alldata.map((item, index) => {
    return {
      radius: [scale * 1.3, scale * 1.5],
      label: {
        textStyle: {
          fontSize: scale / 2,
        },
      },
    };
  });
  let initOptions = {
    title: {
      textStyle: {
        fontSize: scale,
      },
    },
    series: setateData,
  };
  echartsInstance.setOption(initOptions);
  echartsInstance.resize();
}
onMounted(() => {
  initEcharts();
  getData();
  asisEcharts();
  window.addEventListener("resize", asisEcharts);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", asisEcharts);
});
defineExpose({
  asisEcharts,
});
</script>

<style scoped lang="scss"></style>
